package com.zjl.SpringBoot.第12章_web安全;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class MyWebSecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests((registry) -> {
            registry.requestMatchers("/","/static","/login").permitAll()//所有人可以访问
                    .anyRequest().authenticated()//其他都要认证
            ;
        });
        //提供表单登录
        http.formLogin(formLogin -> {
            formLogin.loginPage("/login").permitAll()//设置登录页
                ;
        });//自定义登录页位置

        return http.build();
    }
    @Bean //会导致配置文件的账号密码等失效     查询用户详情   模拟内存保存用户信息
    UserDetailsService userDetailsService(PasswordEncoder passwordEncoder){
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        UserDetails lisi = User.withUsername("lisi")//账号
                .password(passwordEncoder.encode("1"))//密码加密器  加密密码
                .roles("hr")//角色
                .authorities("q1").build();//权限
        UserDetails admin = User.withUsername("admin")//账号
                .password(passwordEncoder.encode("1"))//密码加密器  加密密码
                .roles("admin", "hr")//角色
                .authorities("q2").build();//权限

        inMemoryUserDetailsManager.createUser(lisi);//添加角色
        inMemoryUserDetailsManager.createUser(admin);//添加角色
        return inMemoryUserDetailsManager;
    }
    @Bean //密码的加密器
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
